// 序列
let index = Math.floor(Math.random() * 10000);
//所有元素都有data-flag，节点标识，可由用户创建
export function generateFlag(prefix: string) {
    let flag: string;
    const flags = Array
        .from(document.querySelectorAll<HTMLElement>("[data-flag]"))
        .map(el => el.dataset.flag)
        .filter(f => !!f);
    do {
        flag = `${prefix}-${Math.floor(Math.random() * 100000)}`;
    } while (flags.includes(flag));
    return flag;
}
export function generateId(prefix: string): string {
    return `${prefix}-${Date.now().toString(36)}-${(index++).toString(36)}`;
}
export function queryString(params: Record<string, any>): string {
    return new URLSearchParams(params).toString();
}
export function getUrlParams(url?: string): Record<string, any> {
    const res = <Record<string, any>>{};
    const p = new URLSearchParams(url ?? location.search);
    p.forEach((v, k) => {
        res[k] = v;
    });
    return res;
}
// 获取中心坐标
function getPortPosition(p: Element) {
    const rect = p.getBoundingClientRect();
    return {
        x: rect.left + rect.width / 2,
        y: rect.top + rect.height / 2
    };
}

// 获取当前旋转角度
export function getPortsRotation(inport: HTMLElement, outport: HTMLElement) {
    const from = inport.classList.contains("in-port") ? inport : outport;
    const to = outport.classList.contains("out-port") ? outport : inport;
    const p1 = getPortPosition(from);
    const p2 = getPortPosition(to);
    const dx = p2.x - p1.x;
    const dy = p2.y - p1.y;
    const radians = Math.atan2(dy, dx);
    return (radians * (180 / Math.PI) + 360) % 360 // 转换为0-360度;
}

//计算两个元素的距离,2个元素较小，以元素中心计算
export function calcDistance(holdNode: HTMLElement, dst: HTMLElement) {
    const x = dst.offsetLeft - holdNode.offsetLeft;
    const y = dst.offsetTop - holdNode.offsetTop;
    return Math.pow(x * x + y * y, 0.5);
}

class Http {
    async get(url: string): Promise<Record<string, any>> {
        const res = await fetch(url);
        return await res.json();
    }
    async post(url: string, data: {}): Promise<Record<string, any>> {
        const params = <BodyInit>data;
        const res = await fetch(url, {
            method: "post",
            body: params
        });
        return await res.json();
    }
}
export const http = new Http();


export function openWindow(url: string, second: boolean = false) {
    const screenWidth = window.screen.width;
    const win = window.open(url, second ? "second_win" : "first_win", `width=450, height=520, top=100, left=${screenWidth - 520}`);
    if (!win) {
        alert('请允许弹出窗口！');
    }
    return win;
}

export function showDialog(url: string, dialog: HTMLDialogElement, width: number = 400, height: number = 440) {
    const iframe = dialog.querySelector<HTMLIFrameElement>("iframe")!;
    iframe.style.width = `${width}px`;
    iframe.style.height = `${height}px`;
    iframe.src = url;
    const mask = document.querySelector<HTMLDivElement>(".mask")!;
    mask.style.display = "block";
    dialog.showModal();
}
export function closeDialog(dialog: HTMLDialogElement) {
    const mask = document.querySelector<HTMLDivElement>(".mask")!;
    mask.style.display = "none";
    dialog.querySelector("iframe")!.src = "./view/blank.html";
    dialog.close();
}

export function getStorageValue(key: string): Record<string, any> | undefined {
    const str = storage.getItem(key);
    let json;
    if (str) {
        json = JSON.parse(str);
    }
    return json;
}

export const storage: Storage = (function () {
    const win = parent ?? opener;
    return win ? win.sessionStorage : sessionStorage;
})();
